﻿
function displayForm(ui, fields) {
    $(fields).each(function () {
        var html = '';
        var fieldSelector = '#' + this.ControlType + this.Id;
        var validatorConfig = $.parseJSON(this.ValidatorConfig);
        if (this.ControlType == 'text') {
            displayText(ui, this);
            html = '<div><span class="msg-box" for="' + this.ControlType + this.Id + '"></span></div>';

            var validatorStr = '';
            if (validatorConfig.Required == '1') {
                validatorStr += 'required';
            }
            if (validatorConfig.Format != '-1') {
                validatorStr += ' ' + validatorConfig.Format;
            }
            $(fieldSelector).attr('data-rule', validatorStr);

            //日期
            if (validatorConfig.Format == 'date') {
                $(fieldSelector).addClass('form_datetime');
            }
        } else if (this.ControlType == 'long_text') {
            displayTextArea(ui, this);
            html = '<div><span class="msg-box" for="' + this.ControlType + this.Id + '"></span></div>';

            var validatorStr = '';
            if (validatorConfig.Required == '1') {
                validatorStr += 'required';
            }
            if (validatorConfig.Format != '-1') {
                validatorStr += ' ' + validatorConfig.Format;
            }
            $(fieldSelector).attr('data-rule', validatorStr);
        } else if (this.ControlType == 'rbox') {
            displayRadiobox(ui, this);
            if (validatorConfig.Required == '1') {
                $(fieldSelector).find('input:first').attr('data-rule', 'checked');
            }
            html = '<div><span class="msg-box" for="group_' + this.ControlType + this.Id + '"></span></div>';
        } else if (this.ControlType == 'cbox') {
            displayCheckbox(ui, this);
            if (validatorConfig.Required == '1') {
                $(fieldSelector).find('input:first').attr('data-rule', 'checked');
            }
            html = '<div><span class="msg-box" for="group_' + this.ControlType + this.Id + '"></span></div>';
        } else if (this.ControlType == 'ddlist') {
            displaySelect(ui, this);
            if (validatorConfig.Required == '1') {
                $(fieldSelector).find('select:last').attr('data-rule', 'selectval');
            }
            html = '<div><span class="msg-box" for="' + $(fieldSelector).find('select:last').attr('id') + '"></span></div>';
        }
        $(fieldSelector).attr('field', $.toJSON(this));
        $(fieldSelector).after(html);
    });

    //日期控件
    $(".form_datetime").datepicker({ format: 'yyyy-mm-dd' }).on("changeDate", function (date) {
        if ('days' == date.viewMode) {
            $(".form_datetime").datepicker('hide');
        }
    });
}

function displayText(ui, field) {
    var html = '<label for="' + field.ControlType + field.Id + '">' + field.FieldName + '：</label>'
        + '<input id="' + field.ControlType + field.Id + '" type="text" placeholder="' + field.Memo + '"/>';
    ui.append(html);

}

function displayTextArea(ui, field) {
    var html = '<label for="' + field.ControlType + field.Id + '">' + field.FieldName + '：</label>'
        + '<textarea id="' + field.ControlType + field.Id + '"/>';
    ui.append(html);
}

function displayRadiobox(ui, field) {
    var html = '<fieldset id="' + field.ControlType + field.Id + '" data-role="controlgroup" >' +
        '<legend>' + field.FieldName + '：</legend>';
    var datas = $.parseJSON(field.DataSource);
    if (datas && datas[0] && datas[0].children) {
        var index = 0;
        $(datas[0].children).each(function () {
            var radioId = field.ControlType + field.Id + (++index);
            html += '<input name="group_' + field.ControlType + field.Id + '" id="' + radioId + '" value="' + this.name + '"  type="radio">' +
                    '<label for="' + radioId + '">' + this.name + '</label>';
        });
    }
    html += '</fieldset>';
    ui.append(html);
}

function displayCheckbox(ui, field) {
    var html = '<fieldset id="' + field.ControlType + field.Id + '" data-role="controlgroup" >' +
        '<legend>' + field.FieldName + '：</legend>';
    var datas = $.parseJSON(field.DataSource);
    if (datas && datas[0] && datas[0].children) {
        var index = 0;
        $(datas[0].children).each(function () {
            var radioId = field.ControlType + field.Id + (++index);
            html += '<input name="group_' + field.ControlType + field.Id + '" id="' + radioId + '" value="' + this.name + '"  type="checkbox">' +
                    '<label for="' + radioId + '">' + this.name + '</label>';
        });
    }
    html += '</fieldset>';
    ui.append(html);
}

//支持级联
function displaySelect(ui,field) {
    var html = '<fieldset data-role="controlgroup" id="' + field.ControlType + field.Id + '">' +
    '<legend>' + field.FieldName + '：</legend>';
    //var html = '<div id="' + field.ControlType + field.Id + '">' + '<label>' + field.FieldName + '：</label>';

    var datas = $.parseJSON(field.DataSource);
    var defvals = field.Memo.split(',');
    if (datas && datas[0] && datas[0].children) {
        html += '<select cascad_field="' + field.Id + '" id="' + field.ControlType + field.Id + '0" deep="0">';

        var defval = '--请选择--';
        if (defvals.length > 0) {
            defval = defvals[0];
        }
        html += '<option value="-1">' + defval + '</option>';
        $(datas[0].children).each(function () {
            html += '<option value="' + this.name + '">' + this.name + '</option>';
        });
        html += '</select>';
    }


    //获取深度
    var max_deep = getDataSourceDeep(datas[0]);
    for (var i = 1; i < max_deep; i++) {
        html += '<select cascad_field="' + field.Id + '" deep="' + i + '" id="' + field.ControlType + field.Id + i + '">';

        if (defvals.length > i) {
            defval = defvals[i];
        }
        html += '<option value="-1">' + defval + '</option>';
        html += '</select>';
    }


    html += '</fieldset>';
    //html += '</div>';

    ui.append(html);
    //$('select[cascad_field=' + field.Id + ']').change();
    var onSelectChange = function () {
        var deep = parseInt($(this).attr('deep'));
        var val = $(this).val();
        //重置往后的数据
        for (var i = deep + 1; i < max_deep; i++) {
            var select = $('select[cascad_field=' + field.Id + '][deep=' + i + ']');
            select.empty();
            if (defvals.length > i) {
                defval = defvals[i];
            }
            select.append('<option value="-1">' + defval + '</option>');

            //直接下级
            if (i == deep + 1 && val != '-1') {
                var children = getCurrentData(deep);
                $(children).each(function () {
                    select.append('<option value="' + this.name + '">' + this.name + '</option>');
                });
            }

            select.selectmenu("refresh");
        }
        //select.trigger("validate");
    }

    $('select[cascad_field=' + field.Id + ']').bind('change', onSelectChange);

    var getCurrentData = function (deep) {

        var children = datas[0].children;
        for (var i = 0; i < deep + 1; i++) {
            var val = $('select[cascad_field=' + field.Id + '][deep=' + i + ']').val();
            $(children).each(function () {
                if (val == this.name) {
                    children = this.children;
                    return false;
                }
            });
        }
        return children;
    }
}



//获取数据源深度
function getDataSourceDeep(data) {
    var deep = 0;
    if (data.children && data.children.length>0) {
        var maxDeep = 0;
        $(data.children).each(function () {
            var tdeep = getDataSourceDeep(this);
            if (tdeep > maxDeep) {
                maxDeep = tdeep;
            }
        });
        deep = maxDeep + 1;
    }
    //$('#console').append(data.name + '===>' + deep + '<br/>');
    return deep;
}


function submitForm(ui) {
    ui.trigger("validate");
    if (ui.isValid() == false) {
        return;
    }
    var values = [];
    ui.find('[field]').each(function () {
        var prop = { Id: 0, Value: '' };
        var field = $.parseJSON($(this).attr('field'));
        prop.Id = field.Id;
        if (field.ControlType == 'text' || field.ControlType == 'long_text') {
            prop.Value = $(this).val();
        } else if (field.ControlType == 'rbox') {
            $(this).find('input[type=radio]').each(function () {
                if ($(this).prop('checked') == true) {
                    prop.Value = $(this).val();
                    return false;
                }
            });
        } else if (field.ControlType == 'cbox') {
            $(this).find('input[type=checkbox]').each(function () {
                if ($(this).prop('checked') == true) {
                    prop.Value += '[' + $(this).val() + ']';
                }
            });
        } else if (field.ControlType == 'ddlist') {
            $(this).find('select').each(function () {
                if ($(this).val() == '-1') {
                    prop.Value += '[未指定]';
                } else {
                    prop.Value += '[' + $(this).val() + ']';
                }

            });
        }
        values.push(prop);
    });

    var param = { Values: values, FormId: ui.attr('form_id') };
    ui.executeCommand({
        //执行成功回调
        successCallBack: function (result, totalCount) {
            if ($('#btApply').length > 0) {
                $("#btApply").text("已提交");
                $("#btApply").attr("disabled", "disabled");
            }
            showTips('信息提交成功', 2000, function () {
                if (ui.attr('return_url') != '') {
                    location.href = ui.attr('return_url');
                }
            });
        },
        //执行错误回调
        errorCallback: function (errorCode, msg) {
            showTips(msg);
        }
    }, 'Pub.SubmitForm', param);
}